package com.cb.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.cb.config.AlipayConfig;
import com.cb.dao.UserDao;
import com.cb.dao.UserFilmDao;
import com.cb.pojo.FilmAccess;
import com.cb.pojo.User;
import com.cb.service.UserService;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.security.provider.MD5;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

@Service
public class UserServiceImpl implements UserService {

    Logger logger = Logger.getLogger("com.cb.serviceimpl.UserServiceImpl");

    String s = "";
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserFilmDao userFilmDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String, String> redisCacheTemplate;

    public static final String SCORE_RANK = "score_rank";
    public HashMap<String, Integer> hashMap = new HashMap<>();
    private String yx;

    @Override
    public String userInsert(User user) {
        String password = user.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Password);
        if (user.getVerificationcode().equals(s)) {
            if (userDao.userInsert(user) == 1) {
                return "a";
            } else {
                return "b";
            }
        } else {
            return "验证码有误，请重新发送";
        }
    }

    @Override
    public void VerificationCode(String phone) {
        yx = phone;
        int res = 0;
        String mailServer = "smtp.163.com";
        String loginAccount = "caizhengyufjut@163.com";
        String loginAuthCode = "UJGDUVXWGLBNTCKB";
        String sender = "caizhengyufjut@163.com";
        try {
            // 跟smtp服务器建立一个连接
            Properties p = new Properties();
            // 设置邮件服务器主机名
            p.setProperty("mail.host", mailServer);
            // 发送服务器需要身份验证,要采用指定用户名密码的方式去认证
            p.setProperty("mail.smtp.auth", "true");
            // 发送邮件协议名称
            p.setProperty("mail.transport.protocol", "smtp");

            // 开启SSL加密，否则会失败
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            p.put("mail.smtp.ssl.enable", "true");
            p.put("mail.smtp.ssl.socketFactory", sf);
            // 创建session
            Session session = Session.getDefaultInstance(p,
                    new Authenticator() {
                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            // 用户名可以用QQ账号也可以用邮箱的别名:第一个参数为邮箱账号,第二个为授权码
                            javax.mail.PasswordAuthentication pa = new PasswordAuthentication(loginAccount, loginAuthCode);
                            return pa;
                        }
                    });
            // 设置打开调试状态
            session.setDebug(true);
            // 声明一个Message对象(代表一封邮件),从session中创建
            MimeMessage msg = new MimeMessage(session);
            // 邮件信息封装
            // 1发件人
            InternetAddress sendInternetAddress = new InternetAddress(sender);
            msg.setFrom(sendInternetAddress);
            // 2一个的收件人
            System.out.println(phone);
            InternetAddress receiveInternetAddress = new InternetAddress(phone);
            msg.setRecipient(RecipientType.TO, receiveInternetAddress);
            // 3邮件内容:主题、内容
            Random r = new Random();
            String ss = "";
            for (int i = 0; i <= 5; i++) {
                int ran1 = r.nextInt(9);
                ss += String.valueOf(ran1);
            }
            s = ss;
            String emailContentType = "text/html;charset=utf-8";
            String emailSubject = "验证码";
            msg.setSubject(emailSubject);
            // 发html格式的文本
            msg.setContent(s, emailContentType);
            Transport.send(msg);
            res = 1;
        } catch (Exception e) {
            System.out.println("邮件发送失败: " + e.getMessage());
            res = 0;
        }
    }

    @Override
    public String login(HashMap json, HttpServletRequest request) {
        String username = String.valueOf(json.get("username"));
        String password = String.valueOf(json.get("password"));
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        HttpSession session = request.getSession();
        if (username != null) {
            User user = new User();
            user = userDao.login(username);
            if (user.getPassword().equals(md5Password)) {
                session.setAttribute("username", username);
                session.setAttribute("zzid", user.getZzid());
                session.setAttribute("name", user.getName());
                return username;
            } else {
                return "密码错误";
            }
        } else {
            return "账号不能为空";
        }
    }

    @Override
    public String yzlogin(HashMap json, HttpServletRequest request) {
        String yzm = String.valueOf(json.get("yzm"));
        String phone = String.valueOf(json.get("phone"));
        HttpSession session = request.getSession();
        System.out.println(s);
        if (yzm.equals(s) && yx.equals(phone)) {
            User user = userDao.selectPhoneUser(phone);
            session.setAttribute("username", user.getUsername());
            session.setAttribute("zzid", user.getZzid());
            session.setAttribute("name", user.getName());
            return "登录成功";
        } else {
            return "验证码错误";
        }
    }

    public int redisSelect(FilmAccess filmAccess) {

        return -1;

    }

    @Override
    public void filmaccess(FilmAccess filmAccess) {
        String ypname = filmAccess.getYpname();
        if (redisCacheTemplate.opsForZSet().size(SCORE_RANK)==0){
            userDao.filmaccess(filmAccess);
            redisCacheTemplate.opsForZSet().add(SCORE_RANK,ypname,1);
        }
        else {
            if (redisCacheTemplate.opsForZSet().score(SCORE_RANK,ypname)==null){
                userDao.filmaccess(filmAccess);
                redisCacheTemplate.opsForZSet().add(SCORE_RANK,ypname,1);
            }
            else{
                double score = redisCacheTemplate.opsForZSet().score(SCORE_RANK,ypname);
                int num = (int) score+1;
                redisCacheTemplate.opsForZSet().add(SCORE_RANK,ypname,score+1);
                userDao.filmaccess(filmAccess);
            }
        }

    }

    @Override
    public String joinMemberShip(HashMap json, HttpServletRequest requests) throws AlipayApiException, ParseException {
        HttpSession session = requests.getSession();
        String username = (String) session.getAttribute("username");
        String id = String.valueOf(session.getAttribute("zzid"));
        String yyid = String.valueOf(json.get("yyid"));
        id += yyid + System.currentTimeMillis();
        double vipprice = userDao.selectVipPrice(yyid);

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(id);
        model.setSubject(yyid);
        model.setTotalAmount(String.valueOf(vipprice));
        model.setBody("会员");
        model.setTimeoutExpress("2m");
        model.setProductCode(String.valueOf(session.getAttribute("zzid")));

        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notify_url);
        request.setReturnUrl(AlipayConfig.return_url);
        String form = alipayClient.pageExecute(request).getBody();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endtime = null;
        if (userDao.selectEndTime(yyid, username) == null) {
            endtime = null;
        }
        else{
            endtime = userDao.selectEndTime(yyid, username);
        }
        String now = df.format(new Date());
        System.out.println(now);
        Date nowDate = df.parse(now);
        Date begin = null, end = null;
        int flag = 0;
        if (endtime == null) {
            flag = -1;
        } else {
            flag = endtime.compareTo(nowDate);
        }
        logger.info(String.format("flag: %s",flag));
        if (flag == 1) {
            begin = userDao.selectbegin(yyid,username);
            Calendar cal = Calendar.getInstance();
            cal.setTime(endtime);
            cal.add(Calendar.DATE,30);
            end = cal.getTime();
        } else {
            begin = nowDate;
            Calendar cal = Calendar.getInstance();
            cal.setTime(begin);
            cal.add(Calendar.DATE,30);
            end = cal.getTime();
        }
        if (endtime == null){
            userDao.insertVip(yyid,username,df.parse(df.format(begin)),df.parse(df.format(end)));
        }
        else {
            userDao.updateuservip(yyid, username, df.parse(df.format(begin)),df.parse(df.format(end)));
        }
        return form;
    }

    @Override
    public String yzZzid(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = userDao.yzZzid(String.valueOf(session.getAttribute("username")));
        if (user.getZzid() != null) {
            return "a";
        } else {
            return "b";
        }
    }

    @Override
    public String realNameSystem(HashMap json, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String regex = "\\d{15}(\\d{2}[0-9xX])?";
        String zzid = String.valueOf(json.get("zzid"));
        String username = (String) session.getAttribute("username");
        String name = String.valueOf(json.get("name"));
        String flag;
        if (zzid.matches(regex)) {
            if (userDao.realNameSystem(username, zzid,name) == 1) {
                flag = "验证成功";
            } else {
                flag = "验证失败";
            }
        } else {
            flag = "验证失败";
        }
        return flag;
    }

    @Override
    public String judgmentVip(HashMap json, HttpServletRequest request) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HttpSession session = request.getSession();
        String now = df.format(new Date());
        Date nowDate = df.parse(now);
        Date endDate = userDao.selectEndVipTime(String.valueOf(session.getAttribute("username")));
        if (endDate == null || nowDate.getTime() > endDate.getTime()) {
            return "false";//验证失败
        } else {
            return "true";//验证成功
        }
    }

    @Override
    public String myorderlist(HashMap json, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if(username == null){
            return JSON.toJSONString("请先登录");
        }
        return JSON.toJSONString(userDao.selectOrderListByUserName(username));
    }

    @Override
    public String changepassword(HashMap json, HttpServletRequest request) {
        String username = String.valueOf(json.get("username"));
        String jpassword = String.valueOf(json.get("jpassword"));
        String newPassword = String.valueOf(json.get("newpassword"));
        System.out.println(username+" "+jpassword+" "+newPassword);
        String md5Password = DigestUtils.md5DigestAsHex(jpassword.getBytes());
        String md5Password1 = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        if (md5Password.equals(userDao.login(username).getPassword())){
            userDao.updateUserPassword(username,md5Password1);
            return JSON.toJSONString("修改成功");
        }
        else{
            return JSON.toJSONString("旧密码错误");
        }
    }

}
